<template>
	<view style="display: flex;height: 100vh;flex-direction: column;">
		<js-error mode="bottom" ref="jsError"></js-error>
		<xw-scan></xw-scan>
		<view style="background-color: #fff;margin-bottom: 10px;">
			<view class="search">
				<u-search @click="show = true" :show-action="false" placeholder="搜索" :disabled="true"></u-search>
			</view>
			<!-- <view class="cu-bar search" style="padding: 10px">
				<u-search v-model="barCode" ref="uSearch" :focus="focus" placeholder="请先聚焦后扫描" :show-action="false"
					@search="confirm"></u-search>
				
				<view style="margin-left: 10px; display: flex; flex-direction: column">
					<u-icon @click="show=true" name="list-dot" size="50"></u-icon>
				</view>
			</view> -->
		</view>
		<view>
			<u-popup v-model="show" mode="right" length="90%">
				<view
					style="font-size: 18px;border-bottom: 1px solid #aaa;font-weight: bold;padding: 10px;display: flex;justify-content: space-between;">
					<!-- <u-icon name="/static/image/ss.png" size="65"></u-icon> -->
					<text class=" padding-left-sm" style="color: #3E97B0;">筛选</text>
					<text @click="show=false">关闭</text>
				</view>
				<!-- class="form"  -->
				<u-form class="form" style="padding: 0 10px;" :model="query" ref="uForm" label-position="left">
					<!-- <view class="padding-sm flex">
						
					  <view style="width: 100%"
					      ><u-search
					        placeholder="请扫描存货/货位"
					        v-model="barCode"
					        :show-action="false"
					        @search="confirm()"
					        searchIconSize="26"
							:focus="focus"
					        :inputStyle="inputStyle"
					      ></u-search
					    ></view>
					    <u-icon
					      name="scan"
					      size="60"
					      class="margin-sm-left flex-sub margin-sm-right"
						  @click="search"
					    ></u-icon>
					  </view> -->
					
					<u-form-item class="text-bold" label="仓库:" prop="whcode" label-width="220">
						<u-input placeholder="请输入" v-model="query['basWare.cwhname']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="货位:" prop="pos_code" label-width="220">
						<u-input placeholder="请输入" v-model="query['basPosition.posName']" type="text" maxlength="200"></u-input>
					</u-form-item>
					
					<!-- <u-form-item class="text-bold" label="存货名称:" prop="invName" label-width="220">
						<u-input placeholder="请输入" v-model="query.invName" type="text" maxlength="200"></u-input>
					</u-form-item> -->
					
					<u-form-item class="text-bold" label="产品编码:" prop="viewCode" label-width="220">
						<u-input placeholder="请输入" v-model="query['basInv.viewCode']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="产品名称:" prop="inv_code" label-width="220">
						<u-input placeholder="请输入" v-model="query['basInv.invName']" type="text" maxlength="200"></u-input>
					</u-form-item>
					<u-form-item class="text-bold" label="分类:" prop="invClsName" label-width="220">
						<u-input placeholder="请输入" v-model="query['basInvCls.name']" type="text" maxlength="200"></u-input>
					</u-form-item>
					
				</u-form>
				<!-- <view class="footer">
				<u-button class="btn" type="primary" @click="submit">查询</u-button>
			</view> -->
				<view class=" flex cu-bar tabbar bg-white foot cu-modal-footer">
					<!-- round -->
					<button class="cu-btn  lines-red lg " @click="reset">重置</button>
					<button class="cu-btn  bg-confirm lg margin-left " @click="submit">查询</button>
				</view>
			</u-popup>
			<!-- <u-calendar v-model="startTime" mode="range" @change="startConfirm" max-date="9999"></u-calendar> -->
			<u-picker mode="time" v-model="startTime" @confirm="startConfirm"></u-picker>
			<u-picker mode="time" v-model="startTime2" @confirm="startConfirm2"></u-picker>
		</view>
		<!-- show-summary sum-text="合计" :summary-method="getSummaries" -->
		<next-table class="next-table" style="flex: 1;" :show-header="true" :columns="column" :stripe="true" :fit="false" :border="true"  @pageChange="pageChange"
			:data="datalist" :showPaging="true" :pageIndex="query.pageNo" :pageTotal="pageTotal"  sum-text="合计" show-summary :summary-method="summaryMethod"></next-table>
	
		<view>
			<movable-area class="movable-area1">
				<movable-view class="movable-view" :x="x" :y="y" direction="all">
					<u-button size="mini" @click="search" type="success"
						style="width: 90px; height: 70px; color: #fff; ">
						<view style="font-size: 16px;display: flex; flex-direction: column;text-align: center;">
							<u-icon style="margin: auto;" name="/static/jeesite/sm1.png" size="80"></u-icon>
							<view>扫一扫</view>
						</view>
					</u-button>
		
				</movable-view>
			</movable-area>
		</view>
	</view>
</template>
<script>
	import util from '@/common/fire.js'
	export default {
			options: {
				styleIsolation: 'shared'
			},
			data () {
		        return {
					x: 650, //x坐标
					y: 650, //y坐标
					model:{},
					barCode:'',
					companySelectList:[],
					query: {
						pageNo: 1,
						pageSize: 7,
					},
					inputStyle:{
					  fontSize:'34rpx',
					  marginRight: '10rpx' ,
					},
					show: false,
					startTime: false,
					startTime2: false,
					formDate:'',
					showDate: false,
					focus:false,
		            // pageIndex: 1,
		            pageTotal: 0,
					selectList: [],
		            datalist: [],
		            checkNameList: [],
		            column: [
						// fixed:true,
						{ name: 'xuhao', label: '序号', width:60 ,align:'center',},
						{ name: 'basInv.invName', label: '产品名称', width:150,},
						{ name: 'basPosition.posName', label: '货位', width:80 , },
						{ name: 'iqty', label: '现存量' , width:80,},
						{ name: 'basWare.cwhname', label: '仓库', width:120 , },
						{ name: 'basInvCls.name', label: '分类', width:120 , },
						{ name: 'basInv.viewCode', label: '产品编码', width:120,},
		            ]
		        }
		    },
			onReady() {
				
			},
			onLoad(p) {
				
				if(p.invName){
					this.query['basInv.invName'] = p.invName
					this.query['basInv.viewCode'] = p.viewCode
					this.query['posCode'] = p.posCode || ''
					this.query['basWare.cwhname'] = p.cwhname  || ''
				}
				this.getdatalist()
			},
			onHide() {
				// console.log('页面销毁（onUnload）广播监听事件：xwscan')
				// 销毁广播监听事件
				uni.$off('xwscan', this.BroadcastScanningToObtainData)
			},
			onUnload() {
				// console.log('页面销毁（onUnload）广播监听事件：xwscan')
				// 销毁广播监听事件
				uni.$off('xwscan', this.BroadcastScanningToObtainData)
			},
			onShow() {
				// console.log('页面开启（onLoad）广播监听事件：xwscan')
				// 开启广播监听事件
				uni.$on('xwscan', this.BroadcastScanningToObtainData)
			},
		    methods: {
				handleFocus() {
					var _that = this;
					_that.focus = false;
					setTimeout(() => {
						_that.focus = true;
					}, 500)
				},
				/** 发生声音*/
				sendMp3(name) {
					console.log("=====testClick=====");
					let src = '/static/jeesite/' + name + '.mp3';
					//实例化声音  
					const Audio = uni.createInnerAudioContext();
					Audio.autoplay = true;
					Audio.src = src; //音频地址  
					Audio.play(); //执行播放  
					Audio.onError((res) => {
						console.log(res.errMsg);
						console.log(res.errCode);
					});
					Audio.onPause(function() {
						console.log('end');
						Audio.destroy();
					});
				},
				summaryMethod({columns, data}){
					let sums = [];
					columns.forEach((column, index) => {
					        if (index === 0) {
					            sums[index] = '合计';
					            return;
					        }
					        const values = data.map(item => Number(item[column.name]));
					        const precisions = [];
					        let notNumber = true;
							console.log(values,'values',column.name)
					        values.forEach(value => {
					            if (column.name == 'iqty') {
					                notNumber = false;
					                let decimal = ('' + value).split('.')[1];
					                precisions.push(decimal ? decimal.length : 0);
					            }
					        });
					        const precision = Math.max.apply(null, precisions);
					        if (!notNumber) {
					            sums[index] = values.reduce((prev, curr) => {
					                const value = Number(curr);
					                if (!isNaN(value)) {
					                    return parseFloat((prev + curr).toFixed(Math.min(precision, 20)));
					                } else {
					                    return prev;
					                }
					            }, 0);
					        } else {
					            sums[index] = '';
					        }
					});
					return sums
				},
				invCode(bar, companyCode) {
					let InventoryPrefix = this.vuex_config.InventoryPrefix;
					if (bar.indexOf(InventoryPrefix) != -1) {
						return bar
					} else {
						let code = `inv_${companyCode}_${bar}`
						return code
					}
				},
				BroadcastScanningToObtainData(res) {
					//获取扫描到的条形码
					let barcode = res.code
					
					//判断条形码长度是否大于3
					if(barcode.length > 3){
						//去除换行符
						let newString = barcode.replace('\n;', '');
						
						this.barCode = newString;
						this.confirm()
						//将换行符分割成数组
						// const allItems = newString.split('\n');
						// 	//遍历数组，将每一项添加到arr中
						// 	for(let i = 0;i<allItems.length;i++){
						// 		this.arr.push({
						// 			"content":allItems[i],
						// 			"remarks":this.remarks
						// 		})
						// 	}
					}
				},
				confirm() {
					let _that = this;
					_that.focus = false
					let POSITIONPrefix = _that.vuex_config.POSITIONPrefix;
					let INVPrefix = _that.vuex_config.INVPrefix;
					let bar = encodeURIComponent(this.barCode)
					if (bar.indexOf(POSITIONPrefix) != -1) {
						this.$u.api.m8.getBarInfo({
							barCode: bar,
						}).then((res) => {
							if(res.result == 'true' && !res.errorMsg){
								_that.sendMp3('cg');
								this.query['basPosition.posCode'] = res.basPos.posCode
								this.query['basPosition.posName'] = res.basPos.posName
								this.$forceUpdate()
								this.query.pageNo = 1;
								this.loadData();
							}else{
								_that.sendMp3('sb');
								let message = res.message || res.errorMsg || ''
								_that.$refs.jsError.showError("", message, "error");
							}
							this.barCode = ''
						})
					}else if(bar.indexOf(INVPrefix) != -1){
						this.$u.api.m8.getBarInfo({
							barCode: bar,
						}).then((res) => {
							if(res.result == 'true' && !res.errorMsg){
								_that.sendMp3('cg');
								
								// this.query['basInv.invCode'] = res.basInv.invCode
								this.query['basInv.viewCode'] = res.basInv.viewCode
								this.query['basInv.invName'] = res.basInv.invName
								this.query.pageNo = 1;
								this.loadData();
								this.$forceUpdate()
							}else{
								_that.sendMp3('sb');
								let message = res.message || res.errorMsg || ''
								_that.$refs.jsError.showError("", message, "error");
							}
							this.barCode = ''
						})
					}else{
						_that.sendMp3('bcz');
						_that.$refs.jsError.showError("", "请扫描正确的货位或存货", "error");
						setTimeout(() => {
							_that.focus = true;
							this.barCode = ''
						}, 500)
					}
					
					
					
				// 	let _that = this;
				// 	_that.focus = false
				// 	let InventoryPrefix = _that.vuex_config.InventoryPrefix;
				// 	let PositionPrefix = _that.vuex_config.PositionPrefix;
				// 	let InvBarType = _that.vuex_config.InvBarType;
				// 	let PosBarType = _that.vuex_config.PosBarType;
				// 	let bar = encodeURIComponent(this.barCode)
				// 	if (bar.indexOf(PositionPrefix) != -1) {
				// 		this.$u.api.m8.getBarInfo({
				// 			barCode: bar,
				// 			barType: PosBarType,
				// 			whCode: this.model.whcode || ''
				// 		}).then((res) => {
				// 			if (res.result == 'true') {
				// 				_that.sendMp3('cg');
				// 				setTimeout(() => {
				// 					_that.focus = true;
				// 				}, 500)
				// 				// this.query.whcode = res.data.basWare.cwhcode
				// 				// this.query.posCode = res.data.basPos.posCode
				// 				// this.query.afterPosName = res.data.basPos.posName
				// 				this.query['basPosition.posName'] = res.data.basPos.posName
				// 				this.$forceUpdate()
				// 				this.query.pageNo = 1;
				// 				this.loadData();
				
				// 			} else {
				// 				_that.sendMp3('sb');
				// 				let message = res.message
				// 				_that.$refs.jsError.showError("", message, "error");
				// 				setTimeout(() => {
				// 					_that.focus = true;
				// 				}, 500)
				// 			}
				// 			this.barCode = ''
				// 		})
				// 	} else {
				// 		if (!this.model.companyCode) {
				// 			_that.sendMp3('sb');
				// 			_that.$refs.jsError.showError("", "请先选择公司", "error");
				// 			setTimeout(() => {
				// 				_that.focus = true;
				// 				_that.barCode = ''
				// 			}, 500)
				// 		} else {
				// 			let barCode = this.invCode(bar, this.model.companyCode)
				// 			this.$u.api.m8.getBarInfo({
				// 				barCode: barCode,
				// 				barType: InvBarType,
				// 				companyCode: this.model.companyCode
				// 			}).then((res) => {
				// 				if (res.result == 'true') {
									
				// 					if(res.data.basInv){
				// 						_that.sendMp3('cg');
				// 						setTimeout(() => {
				// 							this.barCode = ''
				// 							// _that.focus = true;
				// 						}, 500)
				// 						this.query['basInv.invCode'] = res.data.basInv?res.data.basInv.invCode:''
				// 						this.query['basInv.invName'] = res.data.basInv?res.data.basInv.invName:''
				// 						this.$forceUpdate()
				// 						this.query.pageNo = 1;
				// 						this.loadData();
				// 					}else{
				// 						_that.sendMp3('sb');
				// 						let message = '请扫描正确的商品编码'
				// 						_that.$refs.jsError.showError("", message, "error");
				// 					}
				// 				} else {
				// 					_that.sendMp3('sb');
				// 					let message = res.message
				// 					_that.$refs.jsError.showError("", message, "error");
				// 					setTimeout(() => {
				// 						this.barCode = ''
				// 						// _that.focus = true;
				// 					}, 500)
				// 				}
				// 				this.barCode = ''
				
				// 			})
				// 		}
				// 	}
				
				},
				search() {
					var _that = this;
					_that.focus = false
					uni.scanCode({
						scanType: ["barCode", "qrCode"],
						// onlyFromCamera: true,
						success: function(res) {
							_that.barCode = res.result;
							_that.confirm()
						},
					});
				},
				makeSound(name){
					console.log("=====testClick=====");
					let src = '/static/'+name+'.mp3';
					//实例化声音  
					const Audio = uni.createInnerAudioContext();
					Audio.autoplay = true;
					Audio.src = src; //音频地址  
					Audio.play(); //执行播放  
					Audio.onError((res) => {
					});
					Audio.onPause(function() {
						console.log('end');
						Audio.destroy();
					});
				},
				async commonSearch(barCode) {
					let that = this
					//扫存货
					if (util.checkBarcode(barCode, this.vuex_config.InventoryPrefix) 
						|| util.checkBarcode(barCode, this.vuex_config.cbatchPrefix)) {
						this.$u.api.mf.getBarInfo({
							barCode,
						}).then(res => {
							if(res.result == 'true'){
								if (!res.error) {
									if(res.data.basInv){
										console.log(res,'res')
										this.query.cinvCode = res.data.basInv.invCode
										this.query.cbatch =  res.data.batchInfo?res.data.batchInfo.u8Batch:''
										
										
										this.$forceUpdate()
										setTimeout(()=>{
											that.makeSound("cg");
										},500)
										that.$u.toast('验证成功！');
									}else{
										setTimeout(()=>{
											that.makeSound("sb");
										},500)
										that.$refs.jsError.showError('', '验证失败！', 'error');
									}
									
								} else {
									setTimeout(()=>{
										that.makeSound("sb");
									},500)
									that.$refs.jsError.showError('', res.error, 'error');
								}
							}else{
								setTimeout(()=>{
									that.makeSound("sb");
								},500)
								that.$refs.jsError.showError('', res.message, 'error');
							}
						})
					}else if(util.checkBarcode(barCode, this.vuex_config.PositionPrefix)){
						this.$u.api.mf.getBarInfo({
							barCode
						}).then(res => {
							if (res.result == 'true') {
								if (!res.error) {
									console.log(res,'res')
										let flag = true
										if (flag) {
											this.query.cposCode = res.data.code
											this.$forceUpdate()
											setTimeout(()=>{
												that.makeSound("cg");
											},500)
											that.$u.toast('成功！');
										} else {
											setTimeout(()=>{
												that.makeSound("sb");
											},500)
											that.$refs.jsError.showError('', '已存在相同货位！', 'error');
										}
						
									// }
						
								} else {
									setTimeout(()=>{
										that.makeSound("sb");
									},500)
									that.$refs.jsError.showError('', res.error, 'error');
								}
							} else {
								setTimeout(()=>{
									that.makeSound("sb");
								},500)
								that.$refs.jsError.showError('', res.message, 'error');
							}
						
						
						})
						
						
					} else {
						setTimeout(()=>{
							that.makeSound("sb");
						},500)
						this.$refs.jsError.showError('', '请扫描正确的条码！', 'error');
					}
				
					setTimeout(() => {
						this.barCode = '';
					}, 500);
				
				},
				startConfirm(e) {
					this.query.ddate_gte = e.year + "-" + e.month + "-" + e.day;
				},
				startConfirm2(e) {
					this.query.ddate_lte = e.year + "-" + e.month + "-" + e.day;
				},
				getStateValue(item){
				  this.query.ctype = item;
				},
				submit() {
					this.query.cinvCode ? this.query.bmustInv = 1 : ''
					this.query.cwhCode ? this.query.bmustWh = 1 : ''
					setTimeout(() => {
						this.query.pageNo = 1;
						this.loadData();
					}, 100);
				},
				reset() {
					this.query = {
						pageNo: 1,
						pageSize: 7,
					};
					this.loadData();
				},
				dateChange(e) {
					console.log(e);
					this.formDate = e.startDate + ' 至 ' + e.endDate ;
					this.query.ddate_gte = e.startDate
					this.query.ddate_lte  = e.endDate
				},
				loadData(){
					this.show = false;
					this.query.pageNo = 1
					this.getdatalist()
				},
		        getdatalist() {
					this.$u.api.m8.whPosInvStockListData(this.query).then((res) => {
						if(!res.list.length){
							this.query.pageNo = 0
						}
						this.datalist = res.list.map((item,index)=>{
							item.xuhao = index+1;
							item['basWare.cwhname'] = item.basWare.cwhname
							// item.weightGgr = util.toFixed2(item.weightGgr);
							// item.weightPs = util.toFixed2(item.weightPs);
							// item.weightSum = util.toFixed2(item.weightSum);
							item['basInv.invName'] = item.basInv?.invName
							item['basInv.viewCode'] = item.basInv?.viewCode
							item['basInv.invStd'] = item.basInv?.invStd
							item['basInv.unitName'] = item.basInv?.unitName
							item['basPosition.posCode'] = item.basPosition?.posCode
							item['basPosition.posName'] = item.basPosition?.posName
							item['basInvCls.name'] = item.basInvCls?.name
							
							return item
						})
						this.pageTotal = Math.ceil(res.count /this.query.pageSize); 
					});
		        },
		        pageChange(index) {
		            this.query.pageNo = index
		            this.getdatalist()
		        },
		    },
		    created() {
		        // this.getdatalist()
		    }
	}
</script>
<style lang="scss">
	
	$all_width: 96rpx;
	$all_height: 96rpx;
	.movable-area1 {
		z-index: 888;
		height: 97vh;
		width: 650rpx;
		position: fixed;
		right: $all_width;
		top: -($all_height + 70rpx);
		pointer-events: none; //此处要加，鼠标事件可以渗透
	
		.movable-view {
			width: $all_width;
			height: $all_height;
			pointer-events: auto; //恢复鼠标事件
	
			image {
				width: $all_width;
				height: $all_height;
			}
		}
	}
	.text-xxl{
		font-size:60rpx;
	}
	page {
		// background-color: #f8f8f8;
		background-color:#e6e6e6;
		height: 100vh;
		overflow: hidden;
		
	}
	.cu-bar {
		min-height: 60px;
	}
	
	.cu-btn {
		font-size: 16px;
		height: 40px;
	}
	
	.foot {
		background: #fff;
	}
	.flex-sub{
		margin-left: 10rpx;
	}
	
	.button {
	  font-size: 32rpx;
	  color: #666666;
	  line-height: 40rpx;
	  padding: 12rpx 40rpx;
	  margin-bottom: 20rpx;
	  margin-right: 10rpx;
	  background: #f7f7f7;
	  border-radius: 180rpx;
	}
	.button:hover {
	  background: #3e97b0;
	  color: #ffffff;
	}

	.uni-group {
		display: flex;
		align-items: center;
	}
	.lable-text {
		text-align: justify;
	}
	
	.u-form-item {
		font-size: 28rpx !important;
		padding: 2px !important;
	}
	.footer {
		position: fixed;
		left: 0;
		bottom: 20px;
		width: 100%;
	}
	.cu-modal-footer {
		padding: 32rpx 32rpx;
		width: 100%;
	
		.cu-btn {
			width: 50%;
		}
	}
	.bg-confirm {
		background: #3e97b0;
		color: #ffffff;
	}
	/deep/.table-empty.data-v-3eadd49d {
		// background: #fff;
	    // height: 63vh !important;
		height: 100% !important;;
		border:none !important;;
	}
	
	/deep/.next-table>.data-v-68ab1c7c{
		height:  calc(100% - 50px);
		background: #fff;
		// overflow-y: hidden;
	}
	
	/deep/.next-table-scroll{
		height: 100%;
		display: flex;
		flex-direction: column;
	}
	/deep/.next-table-fixed{
		flex: 1;
		// overflow: scroll;
	}
	/deep/table-empty{
		flex: 1;
	}
	.text-bold {
		font-size: 17px !important;
		padding:10px 0px !important;
	}
	/deep/.u-form-item{
		padding:10px 0px !important;
	}
</style>